<template>
  <div class="div">
    <div class="function">
      <!-- 产品分类选择器 -->
      <el-dropdown size="large">
        <el-button style="height:50px">
          <span>展示：</span>{{ selectedCategory? selectedCategory : '所有产品' }}
          <el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="selectedCategory = ''">所有产品</el-dropdown-item>
            <el-dropdown-item @click="selectedCategory = '农产品'">农产品</el-dropdown-item>
            <el-dropdown-item @click="selectedCategory = '水产品'">水产品</el-dropdown-item>
            <el-dropdown-item @click="selectedCategory = '加工食品'">加工食品</el-dropdown-item>
            <el-dropdown-item @click="selectedCategory = '工艺品'">工艺品</el-dropdown-item>
            <el-dropdown-item @click="selectedCategory = '茶艺类'">茶艺类</el-dropdown-item>
            <el-dropdown-item @click="selectedCategory = '其他'">其他</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <div>
        <el-dropdown size="large" style="margin-right:50px">
          <el-button style="height:50px">
            <cp-icon name="order-文件夹" style="margin-right:10px"></cp-icon>
            导入
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>Action 1</el-dropdown-item>
              <el-dropdown-item>Action 2</el-dropdown-item>
              <el-dropdown-item>Action 3</el-dropdown-item>
              <el-dropdown-item>Action 4</el-dropdown-item>
              <el-dropdown-item>Action 5</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- 添加产品按钮 -->
        <el-dropdown size="large" style="margin-right:30px">
          <el-button style="height:50px;background:#0caf60;color:#fff" @click="drawer = true">
            <cp-icon name="order-加号" style="margin-right:15px;"></cp-icon>
            添加产品
          </el-button>
        </el-dropdown>
      </div>
    </div>

    <!-- 搜索框和筛选 -->
    <div style="padding: 20px; display: flex; justify-content: space-between; align-items: center;">
      <el-input v-model="searchQuery" placeholder="请输入产品名称搜索" style="width: 1180px;height:50px" size="lager" />
      <el-dropdown size="medium" style="margin-right:230px">
        <el-button style="height:50px">
          <cp-icon name="order-筛选" style="margin-right:15px"></cp-icon>
          筛选
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="filterByCategory('农产品')">农产品</el-dropdown-item>
            <el-dropdown-item @click="filterByCategory('水产品')">水产品</el-dropdown-item>
            <el-dropdown-item @click="filterByCategory('加工食品')">加工食品</el-dropdown-item>
            <el-dropdown-item @click="filterByCategory('工艺品')">工艺品</el-dropdown-item>
            <el-dropdown-item @click="filterByCategory('茶艺类')">茶艺类</el-dropdown-item>
            <el-dropdown-item @click="filterByCategory('其他')">其他</el-dropdown-item>
            <el-dropdown-item @click="clearFilter">清除筛选</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 产品表格 -->
    <el-table :data="paginatedData" style="width: 100%">
      <el-table-column type="selection" width="120" />
      <el-table-column label="产品图片" width="120">
        <template #default="scope">
          <el-image style="width: 50px; height: 50px;" :src="scope.row.image" fit="cover" alt="产品图片" />
        </template>
      </el-table-column>
      <el-table-column label="产品名称" width="220">
        <template #default="scope">
          <div style="display: flex">
            <div>
              <p style="margin: 5px 0">{{ scope.row.name1 }}</p>
              <p style="margin: 5px 0">#ID{{ scope.row.id }}</p>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="价格" width="280">
        <template #default="scope">
          <h4>￥{{ scope.row.price }}</h4>
        </template>
      </el-table-column>
      <el-table-column label="库存" width="280">
        <template #default="scope">
          <span>{{ scope.row.totalInventory }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已售" width="305">
        <template #default="scope">
          <span>已售{{ scope.row.sold }}</span>
          <el-progress show-text="false" :percentage="(scope.row.sold / scope.row.totalInventory * 100).toFixed(1)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button type="text" @click="editProduct(scope.row)" class="edit-btn">编辑</el-button>
          <el-button type="text" @click="deleteProduct(scope.row.id)" class="delete-btn">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div style="margin-left:20px" class="demo-pagination-block">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
                     layout="total, sizes, prev, pager, next, jumper" :total="filteredData.value? filteredData.value.length : 0" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" />
    </div>

    <!-- Drawer 弹出框 -->
    <el-drawer size="50%" v-model="drawer" :with-header="false" custom-class="custom-drawer">
      <div class="top">
        <div class="left">
          <h2 class="drawer-title">产品信息</h2>
          <el-form :model="newProduct" ref="form" label-width="100px" class="product-form">
            <el-form-item label="产品名称">
              <el-input v-model="newProduct.name1" placeholder="请输入产品名称" class="input-field" />
            </el-form-item>
            <el-form-item label="产品分类">
              <el-select v-model="newProduct.productCategory" placeholder="请选择产品分类" style="width: 100%"
                         class="select-field">
                <el-option v-for="item in productCategories" :key="item.value" :label="item.label"
                           :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="价格">
              <el-input v-model="newProduct.price" placeholder="请输入价格" type="number" class="input-field" />
            </el-form-item>
            <el-form-item label="库存">
              <el-input v-model="newProduct.totalInventory" placeholder="请输入库存" type="number" class="input-field" />
            </el-form-item>
            <el-form-item label="已售">
              <el-input v-model="newProduct.sold" placeholder="请输入已售数量" type="number" class="input-field" />
            </el-form-item>

            <!--            <el-form-item label="产品图片">-->
            <!--              <el-upload class="upload-demo" action="" :show-file-list="false" :on-change="handleImageChange"-->
            <!--                         :before-upload="beforeImageUpload">-->
            <!--                <el-button slot="trigger" size="small" type="primary" class="upload-btn">上传图片</el-button>-->
            <!--                <el-button v-if="newProduct.image" @click="removeImage" size="small" type="danger"-->
            <!--                           class="remove-btn">删除图片</el-button>-->
            <!--              </el-upload>-->
            <!--              <div v-if="newProduct.image" style="margin-top: 10px;" class="image-preview">-->
            <!--                <el-image style="width: 100px; height: 100px;" :src="newProduct.image" fit="cover" alt="产品图片" />-->
            <!--              </div>-->
            <!--            </el-form-item>-->
          </el-form>
        </div>
      </div>

      <div class="footer">
        <el-button @click="drawer = false" type="default" class="footer-btn cancel-btn">取消</el-button>
        <el-button @click="addProduct" type="primary" class="footer-btn submit-btn">添加产品</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElLoading } from 'element-plus'; // 引入消息提示和加载组件
import myaxios from '@/Axios/myaxios';

// 控制抽屉组件（弹出框）的显示隐藏
const drawer = ref(false);
// 存储搜索框输入的查询值
const searchQuery = ref('');
// 记录选择的产品分类
const selectedCategory = ref('');

// 用于存储从接口获取的产品列表数据，初始化为空数组
const tableData = ref([]);

// 当前页码
const currentPage = ref(1);
// 每页显示的数量
const pageSize = ref(5);

// 用于控制数据加载时的提示显示
const loading = ref(false);

// 在组件挂载完成后发起获取产品列表数据的请求
onMounted(async () => {
  loading.value = true; // 显示加载提示
  try {
    const response = await myaxios.get('/api/products');
    if (Array.isArray(response.data)) {
      tableData.value = response.data;
    } else {
      console.error('接口返回数据格式不符合预期，期望为数组，实际为:', response.data);
      ElMessage.error('获取产品列表数据格式错误，请联系管理员'); // 给出更友好的错误提示
      tableData.value = [];
    }
  } catch (error) {
    console.error('获取产品列表出错：', error);
    ElMessage.error('获取产品列表时出现错误，请稍后重试'); // 错误提示
    tableData.value = [];
  } finally {
    loading.value = false; // 隐藏加载提示
  }
});

const productCategories = [
  { value: '农产品', label: '农产品' },
  { value: '水产品', label: '水产品' },
  { value: '加工食品', label: '加工食品' },
  { value: '工艺品', label: '工艺品' },
  { value: '茶艺类', label: '茶艺类' },
  { value: '其他', label: '其他' },
];

// 计算分页后的数据
const filteredData = computed(() => {
  if (!Array.isArray(tableData.value)) {
    return [];
  }
  const validCategory = ['农产品', '水产品', '加工食品', '工艺品', '茶艺类', '其他'].includes(selectedCategory.value)? selectedCategory.value : '';
  // 先根据分类过滤
  let filtered = validCategory
    ? tableData.value.filter(item => item.productCategory === validCategory)
    : tableData.value;

  // 再根据搜索框过滤
  if (searchQuery.value) {
    filtered = filtered.filter(item => item.name1.includes(searchQuery.value));
  }

  return filtered;
});

// 根据分页获取数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});

// 分页变更
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

// 筛选操作
const filterByCategory = (category) => {
  selectedCategory.value = category;
};

const clearFilter = () => {
  selectedCategory.value = '';
};

// 新产品的表单数据
const newProduct = ref({
  name1: '',
  productCategory: '',
  price: '',
  totalInventory: '',
  sold: '',
  flag: 0,
  // image: ''
});

// 获取产品列表（当前和之前重复了，可以考虑删除或者整合，这里保留方便查看逻辑）
// const getProducts = async () => {
//   try {
//     const response = await myaxios.get('/api/products');
//     console.log("------------------------------id");
//     console.log("id:", id);
//     if (Array.isArray(response.data)) {
//       tableData.value = response.data;
//     } else {
//       console.error('接口返回数据格式不符合预期，期望为数组，实际为:', response.data);
//       tableData.value = [];
//     }
//   } catch (error) {
//     console.error('获取产品列表出错：', error);
//     tableData.value = [];
//   }
// };

// 添加产品
const addProduct = async () => {
  try {
    console.log(newProduct.value);
    const response = await myaxios.post('/api/products/insert',
      {
        "flag": newProduct.value.flag,
        "name1": newProduct.value.name1,
        "price": newProduct.value.price,
        "productcategory": newProduct.value.productCategory,
        "sold": newProduct.value.sold,
        "totalinventory": newProduct.value.totalInventory
      }
    );
    console.log(response);
    if (response.status === 200 || response.status === 201) {
      // 添加成功后刷新产品列表
      onMounted(); // 重新调用挂载时的获取数据方法刷新数据，也可以考虑优化为只获取新增的数据部分
      drawer.value = false; // 关闭弹出框
      newProduct.value = {
        "flag": 0,
        "name1": "",
        "price": "",
        "productcategory": "",
        "sold": "",
        "totalinventory": ""
      };
    }
  } catch (error) {
    console.error('添加产品出错：', error);
  }
};

// 更新产品
// 编辑产品，打开编辑弹出框并填充产品数据
const editProduct = (product) => {
  // 将新产品表单数据赋值为当前要编辑的产品数据，实现表单预填充
  Object.assign(newProduct.value, product);
  drawer.value = true;
};

// 删除产品，这里完善了参数传递等细节，确保能正确调用接口删除
const deleteProduct = async (productId) => {
  try {
    const response = await myaxios.delete(`/api/products/${productId}`);
    if (response.status === 200) {
      // 删除成功后刷新产品列表
      onMounted(); // 重新调用挂载时的获取数据方法刷新数据，也可以考虑优化为只获取更新后的数据部分
    }
  } catch (error) {
    console.error('删除产品出错：', error);
  }
};

const handleImageChange = (file, fileList) => {
  const reader = new FileReader();
  reader.onload = () => {
    newProduct.value.image = reader.result;
  }
  reader.readAsDataURL(file.raw);
};

const removeImage = () => {
  newProduct.value.image = '';
};
</script>

<style lang="scss" scoped>
.el-table {
  width: 100%;

  .el-table-column {
    margin: 0 50px !important;
  }
}

.el-select__wrapper {
  height: 100%;
}

.edit-btn {
  color: #409EFF;
  margin-right: 10px;
  transition: color 0.3s ease;
  &:hover {
    color: #3382d1;
  }
}

.delete-btn {
  color: #f56c6c;
  transition: color 0.3s ease;
  &:hover {
    color: #f13d3d;
  }
}

.span {
  background: #f4f0ff;
  color: #baa1ff;
}

.span1 {
  background: #fff0e6;
  color: #fea565;
}

.span2 {
  background: #fff0f0;
  color: #fd7777;
}

.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.demo-pagination-block {
  margin-top: 50px;
}

.function {
  display: flex;
  justify-content: space-between;
  width: 1340px;
  padding: 30px;

  .el-dropdown {
    height: 50px;
  }
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}



.custom-drawer {
  padding: 20px;
  border-radius: 10px;
  background-color: #f5f5f5;
}

.drawer-title {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.product-form .el-form-item {
  margin-bottom: 20px;
}

.input-field,
.select-field {
  width: 100%;
  margin-top: 5px;
}

.upload-demo .el-button {
  margin-right: 10px;
}

.upload-btn {
  background-color: #409EFF;
  color: #fff;
  transition: background-color 0.3s ease;
}

.upload-btn:hover {
  background-color: #3382d1;
}

.remove-btn {
  background-color: #f56c6c;
  color: #fff;
  transition: background-color 0.3s ease;
}

.remove-btn:hover {
  background-color: #f13d3d;
}

.image-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}

.footer {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
}

.footer-btn {
  width: 48%;
  font-size: 14px;
  border-radius: 5px;
  transition: all 0.3s ease;
}

.cancel-btn {
  background-color: #e4e7ed;
  border-color: #d3dbe1;
}

.submit-btn {
  background-color: #409EFF;
  color: #fff;
}

.footer-btn:hover {
  opacity: 0.9;
}
</style>

<style lang="scss" scoped>
.el-table {
  width: 100%;

  .el-table-column {
    margin: 0 50px !important;
  }
}

.el-select__wrapper {
  height: 100%;
}

// span {
//   background: #e7f7ef;
//   padding: 5px 10px;
//   color: #16b266;
//   border-radius: 10px;
//   font-size: 12px;
//   display: inline-block;
// }
.span {
  background: #f4f0ff;
  color: #baa1ff;
}

.span1 {
  background: #fff0e6;
  color: #fea565;
}

.span2 {
  background: #fff0f0;
  color: #fd7777;
}

.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.demo-pagination-block {
  margin-top: 50px;
}

.function {
  display: flex;
  justify-content: space-between;
  width: 1340px;
  padding: 30px;

  .el-dropdown {
    height: 50px;
  }
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}



.custom-drawer {
  padding: 20px;
  border-radius: 10px;
  background-color: #f5f5f5;
}

.drawer-title {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.product-form .el-form-item {
  margin-bottom: 20px;
}

.input-field,
.select-field {
  width: 100%;
  margin-top: 5px;
}

.upload-demo .el-button {
  margin-right: 10px;
}

.upload-btn {
  background-color: #409EFF;
  color: #fff;
  transition: background-color 0.3s ease;
}

.upload-btn:hover {
  background-color: #3382d1;
}

.remove-btn {
  background-color: #f56c6c;
  color: #fff;
  transition: background-color 0.3s ease;
}

.remove-btn:hover {
  background-color: #f13d3d;
}

.image-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}

.footer {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
}

.footer-btn {
  width: 48%;
  font-size: 14px;
  border-radius: 5px;
  transition: all 0.3s ease;
}

.cancel-btn {
  background-color: #e4e7ed;
  border-color: #d3dbe1;
}

.submit-btn {
  background-color: #409EFF;
  color: #fff;
}

.footer-btn:hover {
  opacity: 0.9;
}
</style>
